package com.example.dbcms.service.impl;


import com.example.dbcms.domain.Repair;
import com.example.dbcms.domain.Residents;
import com.example.dbcms.mapper.RepairDao;
import com.example.dbcms.mapper.ResidentDao;
import com.example.dbcms.service.RepairService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.List;


@Service
public class RepaireServiceImpl implements RepairService {

    @Autowired
    private RepairDao repairDao;

    @Autowired
    private ResidentDao residentDao;


    @Override
    public PageInfo<Repair> selectAllRepair(Repair repair) {
        PageHelper.startPage(repair.getPageNum(), 10);
        List<Repair> repairList = repairDao.selectAllRepair(repair);
        PageInfo<Repair> pageInfo = new PageInfo<>(repairList);
        return pageInfo;
    }

    @Override
    public Repair getRepair(int id) {
        Font font = new Font("标楷体", Font.BOLD, 16);
        return repairDao.getRepair(id);
    }

    @Override
    public int editRepair(Repair repair) {
        if(repair.getWhetherFromBalance().equals("是")){
            Residents resident = residentDao.getResidentByUserId(repair.getResidentId());
            if(resident!=null){
                String balance = resident.getBalance();
                double residue=Double.parseDouble(balance)-Double.parseDouble(repair.getMoney());
                if(residue<0){
                    return -1;//余额不足
                }else {
                    residentDao.updateBalance(resident.getId(),String.valueOf(residue));
                }
            }else {
                return -2;//该用户不存在
            }
        }
        return repairDao.editRepair(repair);
    }

    @Override
    public int deleteRepair(int id) {
        return repairDao.deleteRepair(id);
    }

    @Override
    public int deleteMultipleRepair(List<Integer> ids) {
        return repairDao.deleteMultipleRepair(ids);
    }

    @Override
    public int addRepair(Repair repair) {
        if(repair.getWhetherFromBalance()!=null&&repair.getWhetherFromBalance().equals("是")){
            Residents resident = residentDao.getResidentByUserId(repair.getResidentId());
            if(resident!=null){
                String balance = resident.getBalance();
                double residue=Double.parseDouble(balance)-Double.parseDouble(repair.getMoney());
                if(residue<0){
                    return -1;//余额不足
                }else {
                    residentDao.updateBalance(resident.getId(),String.valueOf(residue));
                }
            }else {
                return -2;//该用户不存在
            }
        }
        repair.setResidentId(residentDao.getResidentId(repair.getBuildingNo(),repair.getRoomNo()));
        repair.setId(repairDao.getMaxId()+1);
        return repairDao.addRepair(repair);
    }
}
